package cn.lishiyuan.algorithm.queue;

import java.util.Arrays;

/**
 * 顺序队列
 * @param <T>
 */
public class ArrayQueue<T> implements LeeQueue<T>{
    private Object[] array;
    // 队列首位置，取数据位置
    private int front = 0;

    // 队列尾位置，插入数据位置
    private int rear = 0;

    private int count = 0;

    public ArrayQueue(int size) {
        array = new Object[size];
    }


    @Override
    public int count() {
        return count;
    }

    @Override
    public boolean isEmpty() {
        return count == 0;
    }

    @Override
    public void enqueue(T data) {
        if (count == array.length) {
            throw new IllegalStateException("队列已满");
        }
        array[rear] = data;
        // 更新插入位置
        rear = (rear + 1) % array.length;
        count ++;

    }

    @Override
    public T dequeue() {
        if (count == 0) {
            return null;
        }
        T data = (T) array[front];
        array[front] = null;
        front = (front + 1) % array.length;
        count--;
        return data;
    }

    @Override
    public String toString() {
        return Arrays.toString(array);
    }
}
